package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.ApAuthorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP文章作者信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-03-01
 */
@Slf4j
@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements ApAuthorService {
    /**
     * 根据apUserid 查询作者信息
     * @param apUserId
     * @return
     */
//    @Override
//    public AuthorDto findByApUserId(Integer apUserId) {
////        构造查询条件
//        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(ApAuthor::getUserId,apUserId);
////        查询
//        ApAuthor apAuthor = this.getOne(queryWrapper);
//        if(apAuthor != null){
//            return BeanHelper.copyProperties(apAuthor,AuthorDto.class);
//        }
//        return null;
//    }

    //文章服务--保存作者信息
    @Override
    public Integer saveAuthor(AuthorDto dto) {
        //1. 获取APP用户id
        Integer userId = dto.getUserId();
        //2. 根据id查询
        LambdaQueryWrapper<ApAuthor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApAuthor::getUserId, userId);
        ApAuthor apAuthor = getOne(queryWrapper);
        //3. 数据不存在时
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setWmUserId(dto.getWmUserId());
            apAuthor.setUserId(dto.getUserId());
            apAuthor.setCreatedTime(new Date());
        }
        apAuthor.setName(dto.getName());
        apAuthor.setType(dto.getType());
        boolean b = saveOrUpdate(apAuthor);
        if (!b) {
            log.error("新增修改作者失败，apUserId={}", userId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        return apAuthor.getId();
    }

    //查询作者
    @Override
    public ApAuthor findByWmUserId(Integer wmUserId) {
        //  构造查询条件
        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApAuthor::getWmUserId,wmUserId);
        //  查询
        return getOne(queryWrapper);
    }

}
